package com.yonyou.cyxdms.sysAuth.service.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.DALException;
import com.yonyou.cyx.function.exception.DMSAuthException;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.bean.BeanMapperUtil;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.CommonConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.ManageDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthCommonConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.UserAuthConstant;
import com.yonyou.cyxdms.sysAuth.service.dto.AreaManagerDto;
import com.yonyou.cyxdms.sysAuth.service.dto.user.EmpDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.user.EmployeeDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.user.UserDTO;
import com.yonyou.cyxdms.sysAuth.service.entity.DealerInfoPO;
import com.yonyou.cyxdms.sysAuth.service.entity.EmpPo;
import com.yonyou.cyxdms.sysAuth.service.entity.EmployeePO;
import com.yonyou.cyxdms.sysAuth.service.entity.UserPO;
import com.yonyou.cyxdms.sysAuth.service.mapper.*;
import com.yonyou.cyxdms.sysAuth.service.service.EmpService;
import com.yonyou.cyxdms.sysAuth.service.service.UserService;
import com.yonyou.cyxdms.sysAuth.service.service.manage.employee.EmployeeService;
import com.yonyou.cyxdms.sysAuth.service.vo.employee.EmployeeAddVO;
import com.yonyou.cyxdms.sysAuth.service.vo.user.RoleUserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;


/**
 * <p>
 * 人员信息表 服务实现类
 * </p>
 *
 * @author zhangxianchao
 * @since 2018-09-13
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class EmpServiceImpl extends ServiceImpl<EmpMapper, EmpPo> implements EmpService {
    //日志对象
    private static final Logger logger = LoggerFactory.getLogger(EmpServiceImpl.class);
    @Resource
    EmpMapper empMapper;

    @Resource
    EmployeeMapper employeeMapper;

    @Autowired
    UserService userService;

    @Resource
    UserMapper userMapper;


    @Resource
    EmployeeService employeeService;

    @Resource
    DealerInfoMapper dealerInfoMapper;

    @Autowired
    UserOrgPositionMapper userOrgPositionMapper;

    /**
     * 分页查询对应数据
     *
     * @param page           分页对象
     * @param queryCondition 查询条件
     * @author zhangxianchao
     * @since 2018/7/22 0022
     */
    @Override
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public IPage<Map<String, Object>> selectPageBysql(Page page, Map<String, Object> queryCondition) {
        // 获取总条数
        page.setRecords(empMapper.selectPageBySql(page, queryCondition));
        return page;
    }

    /**
     * 根据查询条件返回结果集
     *
     * @param queryCondition 查询条件
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @author zhangxianchao
     * @since 2018/7/22 0022
     */
    @Override
    @Transactional(readOnly = true)
    public List<Map<String, Object>> selectListBySql(Map<String, Object> queryCondition) {
        return empMapper.selectListBySql(queryCondition);
    }

    /**
     * 根据查询条件返回结果集
     *
     * @param id 主键ID
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @author zhangxianchao
     * @since 2018/7/22 0022
     */
    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> getById(Long id) {
        EmpPo emppo = super.getById(id);
        if (emppo != null) {
            return emppo.toMaps();
        } else {
            throw new DALException("查询失败,没有符合条件的数据");
        }
    }

    /**
     * 根据DTO 进行数据新增
     *
     * @param empDTO 页面DTO
     * @return void
     * @author zhangxianchao
     * @since 2018/7/21 0021
     */
    @Override
    public Map<String, Object> insert(EmpDTO empDTO) {
        //对对象进行赋值操作
        EmpPo empPo = new EmpPo(empDTO);
        //执行插入
        save(empPo);

        EmployeePO employeepo = new EmployeePO();
        employeeMapper.insert(employeepo);

        //返回插入的值
        return super.getById(empPo.getEmpId()).toMaps();
    }

    /**
     * 根据DTO 及ID 进行数据更新
     *
     * @param id     主键ID
     * @param empDTO 页面DTO
     * @return void
     * @author zhangxianchao
     * @since 2018/7/21 0021
     */
    @Override
    public Map<String, Object> update(Long id, EmpDTO empDTO) {
        EmpPo empPo = super.getById(id);
        //对对象进行赋值操作
        EmpPo empPo1 = new EmpPo(empDTO);
        BeanUtils.copyProperties(empPo1, empPo);
        empPo.setEmpId(id);
        //执行更新
        this.updateById(empPo);

        EmployeePO employeepo = employeeMapper.getByEmpId(Integer.parseInt(String.valueOf(id)));
        EmployeePO employeepo1 = new EmployeePO();
        BeanUtils.copyProperties(employeepo1, employeepo);
        employeepo.setEmployeeId(employeepo.getEmployeeId());
        employeepo.setEmpId(employeepo.getEmpId());
        employeeMapper.updateById(employeepo);

        return empPo.toMaps();
    }

    /**
     * 根据ID 进行删除数据
     *
     * @param id
     * @return void
     * @author zhangxianchao
     * @since 2018/8/25 0025
     */
    @Override
    public void deleteById(Long id) {
        logger.debug("删除ID:{}", id);
        //根据员工ID来删除用户信息
        userService.deleteUserByEmpId(id);

        int delectCount = empMapper.deleteById(id);
        if (delectCount <= 0) {
            throw new DALException("删除失败,没有符合条件的数据");
        }
    }

    /**
     * 根据ids 进行删除
     *
     * @param ids
     * @return void
     * @author zhangxianchao
     * @since 2018/8/25 0025
     */
    @Override
    @Transactional
    public void deleteBatchIds(String ids) {
        List<Long> longList = StringUtils.convertStrToArray(ids, ",", Long.class);
        //根据员工ID来删除用户信息
        userService.deleteUserByBatchEmpIds(longList);

        int deleteCount = empMapper.deleteBatchIds(longList);
        if (deleteCount != longList.size()) {
            throw new DALException("删除失败,没有符合条件的数据");
        }

        List<Integer> intList = StringUtils.convertStrToArray(ids, ",", Integer.class);
        int delCount = employeeMapper.deleteByEmpIds(intList);
        if (delCount != intList.size()) {
            throw new DALException("删除失败,没有符合条件的数据");
        }
    }

    /**
     * 新增dms人员信息
     * 2019-08-21 update 1.11 po继承DMSBasePo
     * 去除了appID 合并一下PO
     *
     * @param employeeDTO
     * @return java.lang.Long
     * @author zhangsx
     * @since 2018/10/28
     */
    @Override
    public Long addEmployeeFromDms(EmployeeDTO employeeDTO) {
        logger.info("dms人员信息：{}", JSONUtil.objectToJson(employeeDTO));

        DealerInfoPO dealerinfopo = dealerInfoMapper.getDealerCode(employeeDTO.getAppId(), employeeDTO.getDealerCode());
        if (dealerinfopo == null) {
            throw new ServiceBizException("经销商信息不存在,appId=" + employeeDTO.getAppId() + ",dealerCode=" + employeeDTO.getDealerCode());
        }

        Integer companyId = dealerinfopo.getCompanyId();
        Long companyId2 = Long.parseLong(String.valueOf(companyId));

        logger.info("companyId：{}", companyId);

        EmployeePO employeepo = new EmployeePO();
        //   employeePO.setEmployeeName(employeeDTO.getEmployeeName());
        employeepo.setAppId(employeeDTO.getAppId());
        UserDTO dto = employeeDTO.getUserDTO();
        employeepo.setOwnerCode(dto.getDealerCode());
        employeepo.setEmployeeNo(dto.getUserCode());
        employeepo.setUpdatedAt(LocalDateTime.now());
        employeepo.setCreatedAt(LocalDateTime.now());
        employeepo.setIsDeleted(0);
        employeepo.setRecordVersion(0);
        employeepo.setCompanyId(companyId2);
        // 数据入tm_emp 表 返回主键
        // tm_emp 表关联 tm_tmployee 表主键 保存用户的同时数据入emp tm_tmployee表中需要有emp 表主键
        EmpPo empPo = new EmpPo(employeepo);
        empPo.setEmployeeName(StringUtils.isBlank(employeeDTO.getEmployeeName()) ? "员工" :
                employeeDTO.getEmployeeName());
        empPo.setIsDeleted(employeepo.getIsDeleted());
        empPo.setHeadPortrait(StringUtils.isBlank(employeeDTO.getHeadImgUrl()) ? null : employeeDTO.getHeadImgUrl());
        empPo.setUpdatedAt(employeepo.getUpdatedAt());
        empPo.setUpdatedBy(employeepo.getUpdatedBy());
        empPo.setCreatedAt(employeepo.getCreatedAt());
        empPo.setCreatedBy(employeepo.getCreatedBy());
        empPo.setMobilePhone(employeeDTO.getMobilePhone());
        empPo.setIsDeleted(0);
        empPo.setRecordVersion(0);
        empPo.setCompanyId(companyId);
        empMapper.insert(empPo);
        employeepo.setEmpId(Long.parseLong(empPo.getEmpId().toString()));
        employeepo.setOrgId(0L);
        employeeMapper.insert(employeepo);

        //dealerId
        Integer dealerId = userService.getDealerIdByDealerCode(dto.getDealerCode());
        if (dealerId != null) {
            dto.setOrgId(Long.parseLong(String.valueOf(dealerId)));
        } else {
            dto.setOrgId(null);
        }
        logger.info("======获取的经销商=====:{}", dto);
        dto.setUserType(UserAuthConstant.USER_TYPE);
        dto.setEmpId(Long.parseLong(employeepo.getEmployeeId().toString()));
        UserPO userpo = new UserPO();
        userpo.setAppId(dto.getAppId());
        userpo.setEmpId(employeepo.getEmpId().intValue());
        userpo.setUserCode(dto.getUserCode());
        userpo.setPassword(dto.getPassword());
//        userPO.setOwnerCode(dto.getDealerCode());
        userpo.setIsDeleted(0);
        userpo.setRecordVersion(0);
        userpo.setCompanyId(companyId2);
        userpo.setUserStatus(10031001);

        userMapper.insert(userpo);
        return Long.parseLong(employeepo.getEmployeeId().toString());
    }

    /**
     * 更新dms人员信息--五菱
     *
     * @param employeeDTO
     * @return void
     * @author chenzb
     * @since 2019-07-28
     */
    @Override
    public void updateWlEmployeeFromDms(EmployeeDTO employeeDTO) {
        logger.info("更新--五菱dms人员信息：{}", JSONUtil.objectToJson(employeeDTO));

        DealerInfoPO dealerinfopo = dealerInfoMapper.getDealerCode(employeeDTO.getAppId(), employeeDTO.getDealerCode());
        if (dealerinfopo == null) {
            throw new ServiceBizException("经销商信息不存在,appId=" + employeeDTO.getAppId() + ",dealerCode=" + employeeDTO.getDealerCode());
        }

        Integer companyId = dealerinfopo.getCompanyId();
        Long companyId2 = Long.parseLong(String.valueOf(companyId));

        logger.info("companyId：{}", companyId);

        EmployeePO employeepo = new EmployeePO(employeeDTO);
        UserDTO dto = employeeDTO.getUserDTO();
        employeepo.setEmployeeNo(dto.getUserCode());
        // 上游传过来的是的employee_id 通过Id获得emp_id
        LambdaQueryWrapper<EmployeePO> queryWrapper = new QueryWrapper<EmployeePO>().lambda();
        queryWrapper.eq(EmployeePO::getEmployeeId, employeepo.getEmployeeId());
        EmployeePO po = employeeMapper.selectOne(queryWrapper);
        EmpPo empPo = new EmpPo(employeeDTO);
        empPo.setEmpId(Long.parseLong(po.getEmpId().toString()));
        empPo.setMobilePhone(employeeDTO.getMobilePhone());
        empPo.setAppId(employeeDTO.getAppId());
        empPo.setUserCode(po.getEmployeeNo());
        empPo.setUpdatedAt(LocalDateTime.now());
        empPo.setCompanyId(companyId);
        empPo.setIsDeleted(0);
        empPo.setRecordVersion(0);

        // 更新 tm_emp表
        updateById(empPo);

        BeanUtils.copyProperties(employeepo, po);
        po.setEmpId(Long.parseLong(empPo.getEmpId().toString()));
        po.setCompanyId(companyId2);
        po.setIsDeleted(0);
        po.setRecordVersion(0);
        // 更具empId更新 employeeId
        employeeMapper.updateById(po);
        UserPO userpo = new UserPO(dto);
        userpo.setCompanyId(companyId2);
        userpo.setAppId(employeeDTO.getAppId());
        userpo.setIsDeleted(0);
        userpo.setRecordVersion(0);
        userpo.setUserStatus(10031001);
        // 更新 tm_user表
        LambdaUpdateWrapper<UserPO> updateWrapper = new UpdateWrapper<UserPO>().lambda();
        updateWrapper.eq(UserPO::getEmpId, po.getEmpId());
        updateWrapper.eq(UserPO::getCompanyId, po.getCompanyId());
        int update = userMapper.update(userpo, updateWrapper);
        logger.info("更新--五菱dms人员信息-结束");
    }


    @Override
    public Integer getEmployeeByPhone(String phone, String appId) {
        //通过手机号获取对应userCode
        LambdaQueryWrapper<EmpPo> query = new QueryWrapper<EmpPo>().lambda();
        query.eq(EmpPo::getMobilePhone, phone).eq(EmpPo::getAppId, appId);
        List<EmpPo> empPos = empMapper.selectList(query);
        EmpPo empPo = empPos.get(0);
        String userCode = empPo.getUserCode();
        //通过userCode获取对应的userId
        LambdaQueryWrapper<UserPO> useryQuery = new QueryWrapper<UserPO>().lambda();
        useryQuery.eq(UserPO::getUserCode, userCode);
        List<UserPO> userpos = userMapper.selectList(useryQuery);
        return null == userpos || userpos.size() == 0 ? null : userpos.get(0).getUserId();
    }

    @Override
    public List<Integer> getEmployeeByEmployeeName(String employeeName) {
        LambdaQueryWrapper<EmpPo> query = new QueryWrapper<EmpPo>().lambda();
        query.eq(EmpPo::getEmployeeName, employeeName);
        List<EmpPo> empPos = empMapper.selectList(query);
        List<Integer> rlt = new ArrayList<>();
        for (EmpPo epo : empPos) {
            //通过userCode获取对应的userId
            String userCode = epo.getUserCode();
            LambdaQueryWrapper<UserPO> useryQuery = new QueryWrapper<UserPO>().lambda();
            useryQuery.eq(UserPO::getUserCode, userCode);
            List<UserPO> userpos = userMapper.selectList(useryQuery);
            for (UserPO upo : userpos) {
                rlt.add(upo.getUserId());
            }
        }
        return rlt;
    }

    @Override
    public List<EmpDTO> queryAreaManagerByOrgId(Long orgId) {
        List<EmpPo> empPoList = userOrgPositionMapper.queryAreaManagerByOrgId(orgId);
        List<EmpDTO> empDtoList = BeanMapperUtil.copyList(empPoList, EmpDTO.class);
        return empDtoList;
    }

    @Override
    public List<AreaManagerDto> queryAreaManagerAll() {
        List<AreaManagerDto> list = userOrgPositionMapper.queryAreaManagerAll();
        return list;
    }

    /**
     * 更新dms人员信息
     *
     * @param employeeDTO
     * @return void
     * @author zhangsx
     * @since 2018/10/28
     */
    @Override
    public void updateEmployeeFromDms(EmployeeDTO employeeDTO) {
        logger.info("dms人员信息：{}", JSONUtil.objectToJson(employeeDTO));

        DealerInfoPO dealerinfopo = dealerInfoMapper.getDealerCode(employeeDTO.getAppId(), employeeDTO.getDealerCode());
        if (dealerinfopo == null) {
            throw new ServiceBizException("经销商信息不存在,appId=" + employeeDTO.getAppId() + ",dealerCode=" + employeeDTO.getDealerCode());
        }

        Integer companyId = dealerinfopo.getCompanyId();
        logger.info("companyId：{}", companyId);

        EmpPo empPo = new EmpPo(employeeDTO);

        empPo.setCompanyId(companyId);
        empPo.setRecordVersion(0);
        empPo.setIsDeleted(0);

        super.updateById(empPo);
        UserDTO userDTO = employeeDTO.getUserDTO();
        UserPO userpo = new UserPO(userDTO);

        userpo.setCompanyId(Long.parseLong(String.valueOf(companyId)));
        userpo.setRecordVersion(0);
        userpo.setIsDeleted(0);
        userpo.setUserStatus(10031001);

        userService.updateById(userpo);
    }

    /**
     * 新增emp信息
     *
     * @author：李贺
     * @since：2019-09-11
     */
    @Override
    public void addEmp(EmpPo empPo) {
        empMapper.insert(empPo);
    }

    /**
     * 根据IDS获取顾问信息
     *
     * @param userIds
     * @param isContain
     * @param consultantId
     * @return:
     * @auther: tanjie
     * @since: 2019/9/21
     */
    @Override
    public Map<String, Map<String, String>> getEmpInfoByUserId(List<String> userIds, Boolean isContain,
                                                               String consultantId, String appId, String ownerCode) {
        Map<String, Map<String, String>> result = new HashMap<>();
        //反查中包含此id，进行删除
        if (null != consultantId && userIds.contains(consultantId) && isContain == false) {
            userIds.remove(consultantId);
        }
        List<Map<String, Object>> userinfos = empMapper.queryUserInfoByIDS(userIds, isContain, appId, ownerCode);
        for (Map<String, Object> userinfo : userinfos) {
            String id = null;
            String name = null;
            String phone = null;
            try {
                id = userinfo.get("USER_ID").toString();
                name = userinfo.get("EMPLOYEE_NAME").toString();
                phone = userinfo.get("MOBILE_PHONE").toString();
            } catch (Exception e) {
                logger.debug("有顾问信息未配置完全请注意！");
                continue;

            }
            HashMap<String, String> resultUserinfo = new HashMap<>();
            resultUserinfo.put("name", name);
            resultUserinfo.put("phone", phone);
            result.put(id, resultUserinfo);
        }
        return result;
    }

    /**
     * 根据手机号获取组织信息
     *
     * @param code 需要查询角色的CODE
     * @return:
     * @auther: tanjie
     * @since: 2019/10/21
     */
    @Override
    public RoleUserVo getOrginfoByPhone(RoleUserVo roleUserVo, Integer code) {
        return this.empMapper.getOrgInfoByPhone(roleUserVo, code);
    }

    /**
     * 通过userid查emp信息
     *
     * @param:
     * @return:
     * @auther: tanjie
     * @since: 2019/10/22
     */
    @Override
    public EmpDTO queryEmpInfoByUserId(Long userId) {
        UserPO userpo = userMapper.selectById(userId);
        EmpPo empPo = empMapper.selectById(userpo.getEmpId());
        return null == empPo ? null : BeanMapperUtil.copyProperties(empPo, EmpDTO.class);
    }

    @Override
    public EmpPo getEmpInfoByOpenId(String strOpenid, String appId) {
        EmpDTO empDTO = new EmpDTO();
        QueryWrapper<EmpPo> empPoQueryWrapper = new QueryWrapper<>();
        empPoQueryWrapper.eq("open_id", strOpenid).eq("app_id", appId);
        EmpPo empPo = empMapper.selectOne(empPoQueryWrapper);
        if (empPo == null) {
            throw new ServiceBizException("open_id未绑定");
        }
        return empPo;
    }

    @Override
    public Integer getEmpCountByPhone(String phone, String appId) {
        QueryWrapper<EmpPo> empPoQueryWrapper = new QueryWrapper<>();
        empPoQueryWrapper.eq("MOBILE_PHONE", phone).eq("app_id", appId);
        List<EmpPo> empPos = empMapper.selectList(empPoQueryWrapper);
        return empPos.size();
    }

    /**
     * 新增员工时校验员工身份证号
     *
     * @auther: 李贺
     * @since: 2019/11/12
     */
    @Override
    public EmployeeAddVO checkCertificateId(String certificateid) {
        EmployeeAddVO employeeAddVO = new EmployeeAddVO();
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String appId = loginInfoDto.getAppId();
        QueryWrapper<EmpPo> empPoQueryWrapper = new QueryWrapper<>();
        empPoQueryWrapper.eq("CERTIFICATE_ID", certificateid).eq("APP_ID", appId);
        List<EmpPo> empPos = empMapper.selectList(empPoQueryWrapper);
        if (empPos.size() == 0) {
            employeeAddVO.setType(1);
        } else {
            if (empPos.size() > 1) {
                throw new DMSAuthException(SysAuthCommonConstants.ERROR_CODE_994, "当前身份证号绑定人员过多，请联系管理员");
            }
            EmpPo empPo = empPos.get(0);
            Long empId = empPo.getEmpId();
            QueryWrapper<EmployeePO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("EMP_ID", empId)
                    .eq("APP_ID", appId)
                    .eq("VALID_STATUS", ManageDictCodeConstants.STATUS_IS_YES)
                    .eq("EMPLOYEE_STATUS", ManageDictCodeConstants.EMPLOYEE_ISJOB);
            List<EmployeePO> employeepos = employeeMapper.selectList(queryWrapper);
            if (empPo.getUserStatus() == ManageDictCodeConstants.STATUS_QY && empPo.getIsOnjob() == ManageDictCodeConstants.EMPLOYEE_ISJOB && employeepos.size() > 0) {
                employeeAddVO.setType(2);
                employeeAddVO.setEmployeeNo(employeepos.get(0).getEmployeeNo());
            } else {
                String employeeNo = employeeMapper.selectMaxNo(empId, loginInfoDto.getCompanyId());
                employeeAddVO = employeeService.findEmployeeByNo(employeeNo, loginInfoDto.getCompanyId());
                employeeAddVO.setType(3);
            }
        }
        return employeeAddVO;
    }


    /**
     * 批量获取EMP信息
     *
     * @param:
     * @return:map<userid,EmpDTO>
     * @auther: tanjie
     * @since: 2019/10/22
     */
    @Override
    public Map<Long, EmpDTO> queryEmpInfoByUserIds(List<Long> ids) {

        Map<Long, EmpDTO> result = new HashMap<>();
        //每批处理的用户记录数
        int dealCount = 2000;
        int listCount = ids.size();
        if (ids != null && listCount > 0) {
            if (ids.size() <= dealCount) {
                this.queryEmpInfoByUserIdsOld(result, ids);
            } else {
                int batchNum = listCount / dealCount;
                if (batchNum * dealCount < listCount) {
                    batchNum = batchNum + 1;
                }
                for (int i = 0; i < batchNum; i++) {
                    if (i == (batchNum - 1)) {
                        this.queryEmpInfoByUserIdsOld(result, ids.subList(i * dealCount, listCount));
                    } else {
                        this.queryEmpInfoByUserIdsOld(result, ids.subList(i * dealCount, (i + 1) * dealCount));
                    }
                }
            }
        }
        return result;
    }

    /**
     * 功能说明    : 查询用户信息
     * 创建者         : Administrator
     * 修改日期    : 2020年2月28日
     *
     * @param result
     * @param ids
     */
    private void queryEmpInfoByUserIdsOld(Map<Long, EmpDTO> result, List<Long> ids) {
        List<UserPO> userpos = userMapper.selectBatchIds(ids);
        Map<Integer, Integer> empTemp = new HashMap<>();
        userpos.stream().forEach(e -> empTemp.put(e.getEmpId(), e.getUserId()));
        Set<Integer> empids = empTemp.keySet();
        //CMS增加用户空判断，接口数据ids中所有的创建人信息都为-1，empIDS无法查询到具体人员
        if (empids != null && empids.size() > 0) {
            List<EmpPo> empPos = empMapper.selectBatchIds(empids);
            List<EmpDTO> empdtos = BeanMapperUtil.copyList(empPos, EmpDTO.class);
            for (EmpDTO empDTO : empdtos) {
                Integer userId = empTemp.get(empDTO.getEmpId().intValue());
                result.put(userId.longValue(), empDTO);
            }
        }
    }


    /**
     * CODE批量获取EMP信息
     *
     * @param:
     * @return:map<userid,EmpDTO>
     * @auther: tanjie
     * @since: 2019/10/22
     */
    @Override
    public Map<String, EmpDTO> queryEmpInfoByUserCodes(List<String> codes, String appId) {
        LambdaQueryWrapper query = null;
        Map<String, EmpDTO> resultMap = new HashMap<>();
        for (String code : codes) {
            query = new QueryWrapper<UserPO>().lambda().eq(UserPO::getUserCode, code).
                    eq(UserPO::getAppId, appId).last(" LIMIT 1");
            UserPO userpo = userMapper.selectOne(query);
            if (null != userpo) {
                Integer empId = userpo.getEmpId();
                EmpPo empPo = empMapper.selectById(empId);
                if (null != empPo) {
                    resultMap.put(code, BeanMapperUtil.copyProperties(empPo, EmpDTO.class));
                }
            }
        }
        return resultMap;
    }

    @Override
    public RoleUserVo getOrgInfoByPhoneAndOwnerCode(RoleUserVo roleUserVo, Integer dcrcCommissioner) {
        return this.empMapper.getOrgInfoByPhoneAndOwnerCode(roleUserVo, dcrcCommissioner);
    }

    @Override
    public List<Map<String, String>> consultantVerification(List<EmployeeDTO> consultantList) {

        List<Map<String, String>> rlt = new ArrayList<>();
        for (EmployeeDTO dto : consultantList) {
            String appId = dto.getAppId();
            String ownerCode = dto.getDealerCode();
            String phone = dto.getMobilePhone();
            String name = dto.getEmployeeName();
            RoleUserVo roleUserVo = new RoleUserVo();
            roleUserVo.setAppId(appId);
            roleUserVo.setOwnerCode(ownerCode);
            roleUserVo.setPhone(phone);
            RoleUserVo vo = this.empMapper.consultantVerification(roleUserVo, CommonConstants.DCRC_COMMISSIONER);
            if (null == vo) {
                Map<String, String> map = new HashMap();
                map.put("dealerCode", ownerCode);
                map.put("consultantName", name);
                map.put("consultantPhone", phone);
                rlt.add(map);
            }
        }

        return rlt;
    }


}
